﻿using ConfExpert.Forms.Base;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevTeam;
using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Forms.Araclar
{
    public partial class Talimatlar : XForm
    {
        public Talimatlar()
        {
            InitializeComponent();
        }

        BindingSource bs2;
        private void Talimatlar_Load(object sender, EventArgs e)
        {
            gridView1.Init("GetTalimatlar");
            bs2 = gridView1.AddDetailGrid(gridView2, "TalimatTurId");

            gridView1.AddAutoIncrementalPK("TalimatTurId");
            gridView2.AddAutoIncrementalPK("TalimatId");
            gridView1.AddColumn("Adet", typeof(int), "COUNT(Child({FK}).TalimatId)");
            gridView1.FormatAsNumber(0, "Adet");
            gridView1.MakeColumnInvisible("TalimatTurId");
            gridView2.MakeColumnInvisible("DosyaId", "UserId", "Notes");
            gridView2.SetCaptions("TalimatId:#", "Adi:Konusu");
            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;

            gridView1.AddSummary("Adet");
            gridView2.AddSummary();

            richEditControl1.DataBindings.Add("Text", bs2, "Notes");

            //TODO: TIP: If you want to force focus to newly added rows, try setting the GridView's OptionsNavigation.AutoFocusNewRow property to True.

            //gridView1.DragObjectDrop += new DevExpress.XtraGrid.Views.Base.DragObjectDropEventHandler(gridView1_DragObjectDrop);
            this.DragEnter += new DragEventHandler(Attachments_DragEnter);
            this.DragDrop += new DragEventHandler(Attachments_DragDrop);
            gridView2.Click += new EventHandler(gridView2_Click);

            GridManager gm1 = GridManager.GetManager(gridView1);
            gm1.GridMenu.AddMenu("Buraya", Buraya);

            GridManager gm = GridManager.GetManager(gridView2);
            gm.GridMenu.AddMenu("Aç", Ac);

            if (ytk(244))
            {
                gm.GridMenu.AddMenu("Değiştir", Degistir);
                gm.GridMenu.AddMenu("Taşı", Tasi);
                gm.GridMenu.AddMenu("Sil", Sil);

                this.AllowDrop = true;
                gridView1.EnableNewRow();
            }
            else
            {
                gridView1.MakeReadOnly();
                gridView2.MakeReadOnly();
                btnKaydet.Visibility =
                btnEkle.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            }

            gridView2.ShowingEditor += gridView2_ShowingEditor;
            btnEkle.ItemClick += btnNewRow_ItemClick;
            btnKaydet.ItemClick += btnKaydet_ItemClick;

            gridView1.RowCellStyle += new DevExpress.XtraGrid.Views.Grid.RowCellStyleEventHandler(gridView2_RowCellStyle);
            gridView2.RowCellStyle += new DevExpress.XtraGrid.Views.Grid.RowCellStyleEventHandler(gridView2_RowCellStyle);
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
            //gridView2.ShowFindPanel();

            richEditControl1.DocumentLoaded += richEditControl1_DocumentLoaded;
            richEditControl1_DocumentLoaded(null, null);

            gridView1.SetViewCaption("Kategori");
            gridView2.SetViewCaption("Talimatlar");
        }

        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            gridView2.BestFitColumns();
        }

        void richEditControl1_DocumentLoaded(object sender, EventArgs e)
        {
            richEditControl1.Document.SetPageBackground(Color.FromArgb(236, 236, 225));
            richEditControl1.Document.DefaultCharacterProperties.FontSize = 16;
            richEditControl1.Document.DefaultCharacterProperties.FontName = "Calibri";
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.EndEditing();
            gridView2.EndEditing();
            gridView1.UpdateAll("", "TalimatTur", "", "Talimat");
        }

        void btnNewRow_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView2.MoveLast();
            gridView2.MakeRowVisible(gridView2.FocusedRowHandle);

            gridView2.AddNewRow();
        }

        void gridView2_Click(object sender, EventArgs e)
        {
            GridHitInfo hi = gridView2.CalcHitInfo(gridControl2.PointToClient(MousePosition));
            if ((hi.InRow || hi.InRowCell) && gridView2.FocusedRowHandle > -1)
            {
                //txtInfo.Caption = gridView2.GetFocusedRowCellDisplayText("Adi");
                if (gridView2.FocusedColumn.FieldName == "Ext")
                {
                    //Guid ID = (Guid)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "DosyaId");
                    int DosyaId = intParse(gridView2.GetFocusedRowCellValue("DosyaId"));
                    if (DosyaId > 0)
                    {
                        this.Cursor = Cursors.WaitCursor;
                        DataTable t = Session.DataManager.ExecuteDataTable("GetDoc", DosyaId);

                        //GetDetails("Attachment", "GetAttachment", DosyaId, string.Empty);
                        //string FileName  = (string)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FileName");
                        //ByteArrayToFile(FileName, ds.Dosya.FindByDosyaId(DosyaId).BLOB);
                        FileManager.RunTempFile(t.Rows[0]["DosyaAdi"].ToString(), t.Rows[0]["BLOB"] as byte[]);
                        this.Cursor = Cursors.Default;
                    }
                }
            }
        }

        void gridView2_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            GridView view = sender as GridView;

            if (e.RowHandle == view.FocusedRowHandle)
                e.Appearance.BackColor = Color.YellowGreen; // SystemColors.ControlDark;
            else
                e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);

            if (e.Column.FieldName == "Ext")
            {
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                e.Appearance.ForeColor = Color.DarkOrchid;
            }
        }


        void Attachments_DragDrop(object sender, DragEventArgs e)
        {
            int TalimatTurId = gridView1.GetFocusedDataRow()["TalimatTurId"].ToInt();
            if (TalimatTurId < 0)
            {
                ShowErrorMessage("Ekleyeceğiniz talimatın türünü seçmediniz!");
                return;
            }

            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            foreach (string file in files)
            {
                FileInfo fi = new FileInfo(file);

                byte[] bArr = FileManager.Read(fi.FullName);

                ExecuteNonQuery("AddDoc", 0, fi.Name, fi.Extension, bArr, WhoAmI, "Talimat", TalimatTurId);
                Notify("'" + fi.Name + "' eklendi.");
            }

            gridView1.RefreshDataSource("GetTalimatlar");
            gridView1.FocusedRowHandle = gridView1.LocateByValue("TalimatTurId", TalimatTurId);
            gridView1.MakeRowVisible(gridView1.FocusedRowHandle);
            gridView2.BestFitColumns();
            //gridView2.Columns["Notes"].Width = 400;
        }

        void Attachments_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
                e.Effect = DragDropEffects.All;
        }



        void gridView2_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //if (gvListe.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
            e.Cancel = (
                //gridView2.GetFocusedRowCellValue("UserId").ToInt() != WhoAmI || 
                gridView2.FocusedColumn.FieldName == "Ext");
            //e.Cancel = (gvCounting.GetRowCellValue(gvCounting.FocusedRowHandle, "isReadOnly").ToString() == bool.TrueString);
        }


        private void Degistir(object sender, EventArgs e)
        {
            int TalimatTurId = gridView1.GetFocusedDataRow()["TalimatTurId"].ToInt();
            if (TalimatTurId < 0)
            {
                ShowErrorMessage("Ekleyeceğiniz talimatın türünü seçmediniz!");
                return;
            }

            if (gridView2.GetFocusedRowCellValue("DosyaId") != null)
            {
                int DosyaId = intParse(gridView2.GetFocusedRowCellValue("DosyaId"));
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (openFileDialog1.OpenFile() != null)
                        {
                            FileInfo fi = new FileInfo(openFileDialog1.FileName);

                            byte[] bArr = FileManager.Read(openFileDialog1.FileName);
                            ExecuteNonQuery("UpdDoc", DosyaId, fi.Name, fi.Extension, bArr, WhoAmI, "Talimat", TalimatTurId);
                            gridView2.BestFitColumns();
                            Notify("'" + fi.Name + "' güncellendi.");
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        private void Sil(object sender, EventArgs e)
        {
            int TalimatTurId = gridView1.GetFocusedDataRow()["TalimatTurId"].ToInt();
            string SilinecekTalimatlar = gridView2.GetSelectedValues("TalimatId");

            if (SilinecekTalimatlar != string.Empty)
                if (XtraMessageBox.Show("Emin misiniz?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    ExecuteNonQuery("DelDocToplu", SilinecekTalimatlar);

                    Notify("Silindi.");
                    gridView1.RefreshDataSource("GetTalimatlar");
                    gridView1.FocusedRowHandle = gridView1.LocateByValue("TalimatTurId", TalimatTurId);
                    gridView1.MakeRowVisible(gridView1.FocusedRowHandle);
                    gridView2.BestFitColumns();
                }
        }

        string TasinacakTalimatlar = string.Empty;
        private void Tasi(object sender, EventArgs e)
        {
            TasinacakTalimatlar = gridView2.GetSelectedValues("TalimatId");
        }

        private void Buraya(object sender, EventArgs e)
        {
            int TalimatTurId = gridView1.GetFocusedDataRow()["TalimatTurId"].ToInt();
            if (TalimatTurId < 0)
            {
                ShowErrorMessage("Geçerli bir talimat türü seçmediniz!");
                return;
            }

            ExecuteNonQuery("TasiDoc", TasinacakTalimatlar, TalimatTurId);

            Notify("Taşındı.");
            gridView1.RefreshDataSource("GetTalimatlar");
            gridView1.FocusedRowHandle = gridView1.LocateByValue("TalimatTurId", TalimatTurId);
            gridView1.MakeRowVisible(gridView1.FocusedRowHandle);
            gridView2.BestFitColumns();
        }

        private void Ac(object sender, EventArgs e)
        {
            gridView2_Click(null, null);
        }

    }
}
